package com.chhuang.system.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chhuang.system.consts.SysConstants;
import com.chhuang.system.po.ChMenu;
import com.chhuang.system.po.ChRole;
import com.chhuang.system.po.ChRoleMenuMap;
import com.chhuang.system.po.ChUser;
import com.chhuang.system.po.ChUserRoleMap;
import com.chhuang.system.service.IChMenuService;
import com.chhuang.system.service.IChRoleMenuMapService;
import com.chhuang.system.service.IChRoleService;
import com.chhuang.system.service.IChUserRoleMapService;
import com.chhuang.system.service.IChUserService;
import com.chhuang.utils.Assert;
import com.chhuang.utils.config.SysConfig;
import com.chhuang.utils.string.Md5Util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/system/login")
public class LoginController {
	private static final Log log = LogFactory.getLog(ChUserController.class);

	@Autowired
	private IChUserService chUserService;
	@Autowired
	private IChRoleService chRoleService;
	@Autowired
	private IChMenuService chMenuService;
	@Autowired
	private IChUserRoleMapService chUserRoleMapService;
	@Autowired
	private IChRoleMenuMapService chRoleMenuMapService;
	
	/**
	 * 登录验证用户和密码
	 * @param username
	 * @param password
	 * @param checkCode
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/checkLogin" ,method=RequestMethod.POST)
	@ResponseBody
	public Object checkLogin(String username,String password,String checkCode,HttpServletRequest request) throws Exception{
		JSONObject json = new JSONObject();

		if(Assert.isValidString(username) && Assert.isValidString(password) && Assert.isValidString(checkCode)){
			HttpSession session = request.getSession(false);
			String sessionCode = (String) session.getAttribute(SysConfig.getValue(SysConstants.Config.CHECK_CODE));
			if(Assert.isValidString(sessionCode) && sessionCode.equalsIgnoreCase(checkCode)){
				List<ChUser> users = chUserService.findByUsername(username);
				if(Assert.isValidCollection(users) && users.get(0)!=null){
					ChUser user = users.get(0);
					if(user.getPassword().equals(Md5Util.md5(password, username))){
						List<ChUserRoleMap> userRoleMaps = chUserRoleMapService.findByUserId(user.getUserId());
						if(Assert.isValidCollection(userRoleMaps)){
							if(userRoleMaps.size()==1){
								ChRole role = chRoleService.findByPrimaryKey(userRoleMaps.get(0).getRoleId());
								List<ChRoleMenuMap> roleMenuMaps = chRoleMenuMapService.findByRoleId(role.getRoleId());
								if(Assert.isValidCollection(roleMenuMaps)){
									ChMenu menu = chMenuService.findByPrimaryKey(roleMenuMaps.get(0).getMenuId());
									json.put(SysConstants.URL, menu.getUrl());
									json.put(SysConstants.Status.SUCCESS, true);
									session.setAttribute(SysConstants.USER_ID, user.getUserId());
									session.setAttribute(SysConstants.USERNAME, user.getUsername());
									session.setAttribute(SysConstants.NICKNAME, user.getNickname());
									session.setAttribute(SysConstants.ROLE_ID, role.getRoleId());
									session.setAttribute(SysConstants.ROLE_NAME, role.getRoleName());
									log.debug(username+"登录成功");
								}else{
									json.put(SysConstants.Status.SUCCESS, false);
									json.put(SysConstants.Status.RESULT, "用户"+username+"角色"+role.getRoleName()+"没有配置菜单");
									log.debug(username+"登录失败：用户"+username+"角色"+role.getRoleName()+"没有配置菜单");
								}
							}else{
								JSONArray roleArray = new JSONArray();
								for(ChUserRoleMap userRoleMap : userRoleMaps){
									ChRole role = chRoleService.findByPrimaryKey(userRoleMap.getRoleId());
									roleArray.add(role);
								}
								json.put(SysConstants.Status.SUCCESS, true);
								session.setAttribute(SysConstants.USER_ID_WIDTHOUT_ROLE, user.getUserId());
								session.setAttribute(SysConstants.USERNAME_WIDTHOUT_ROLE, user.getUsername());
								session.setAttribute(SysConstants.NICKNAME_WIDTHOUT_ROLE, user.getNickname());
								json.put(SysConstants.HAS_SOME_ROLES, true);
								json.put(SysConstants.ROLES, roleArray);
								log.debug(username+"验证成功,需要选择角色");
							}
						}else{
							json.put(SysConstants.Status.SUCCESS, false);
							json.put(SysConstants.Status.RESULT, "用户"+username+"没有配置角色");
							log.debug(username+"登录失败：用户"+username+"没有配置角色");
						}
					}else{
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "密码有误");
						log.debug(username+"登录失败：密码有误");
					}
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户名不存在");
					log.debug(username+"登录失败：用户名不存在");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "验证码有误");
				log.debug(username+"登录失败：输入的验证码:"+checkCode+",与内存中的验证码:"+sessionCode+",不相同");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "传入参数有误");
		}
		
		return json;
	}
	
	/**
	 * 多角色用户登录验证通过后需要选择一个角色
	 * @param roleId
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/selectRole" ,method=RequestMethod.POST)
	@ResponseBody
	public Object selectRole(String roleId,HttpServletRequest request) throws Exception{
		JSONObject json = new JSONObject();
		
		HttpSession session = request.getSession(false);
		String userId = (String) session.getAttribute(SysConstants.USER_ID_WIDTHOUT_ROLE);
		String username = (String) session.getAttribute(SysConstants.USERNAME_WIDTHOUT_ROLE);
		String nickname = (String) session.getAttribute(SysConstants.NICKNAME_WIDTHOUT_ROLE);
		if(Assert.isValidString(roleId) && Assert.isValidString(userId) 
				&& Assert.isValidString(username) && Assert.isValidString(nickname)){
			ChRole role = chRoleService.findByPrimaryKey(roleId);
			if(role!=null){
				List<ChRoleMenuMap> roleMenuMaps = chRoleMenuMapService.findByRoleId(role.getRoleId());
				if(Assert.isValidCollection(roleMenuMaps)){
					ChMenu menu = chMenuService.findByPrimaryKey(roleMenuMaps.get(0).getMenuId());
					json.put(SysConstants.URL, menu.getUrl());
					json.put(SysConstants.Status.SUCCESS, true);
					session.removeAttribute(SysConstants.USER_ID_WIDTHOUT_ROLE);
					session.removeAttribute(SysConstants.USERNAME_WIDTHOUT_ROLE);
					session.removeAttribute(SysConstants.NICKNAME_WIDTHOUT_ROLE);
					session.setAttribute(SysConstants.USER_ID, userId);
					session.setAttribute(SysConstants.USERNAME, username);
					session.setAttribute(SysConstants.NICKNAME, nickname);
					session.setAttribute(SysConstants.ROLE_ID, role.getRoleId());
					session.setAttribute(SysConstants.ROLE_NAME, role.getRoleName());
					log.debug(username+"登录成功");
				}else{
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "用户"+username+"角色"+role.getRoleName()+"没有配置菜单");
					log.debug(username+"登录失败：用户"+username+"角色"+role.getRoleName()+"没有配置菜单");
				}
			}else{
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "角色不存在");
				log.debug(username+"登录失败：角色不存在");
			}
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "登录失败");
			log.debug(username+"登录失败：roleId为空，或者username为空");
		}
		
		return json;
	}
	
	/**
	 * 退出系统
	 * @param request
	 * @return
	 */
	@RequestMapping("/logout")
	@ResponseBody
	public Object logout(HttpServletRequest request){
		JSONObject json = new JSONObject();
		HttpSession session = request.getSession(false);
		if(session.getAttribute(SysConstants.USERNAME)!=null){
			session.removeAttribute(SysConstants.USER_ID);
			session.removeAttribute(SysConstants.USERNAME);
			session.removeAttribute(SysConstants.ROLE_ID);
			session.removeAttribute(SysConstants.ROLE_NAME);
			session.removeAttribute(SysConstants.NICKNAME);
		}
		json.put(SysConstants.Status.SUCCESS, true);
		return json;
	}
}
